package org.oschina.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.oschina.helper.cache.ICacheHelper;
import org.oschina.util.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * 请求间隔拦截器
 */
public class RequestIntervalInterceptor extends HandlerInterceptorAdapter {

	private final static String REQUEST_INTERVAL_CACHE="REQUEST_INTERVAL_CACHE";
	private final static int MAX_REQUEST_COUNT=20;
	private final static int REQUEST_INTERVAL=1;
	
	@Autowired
	private ICacheHelper cacheHelper;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
	{
		String key=REQUEST_INTERVAL_CACHE+"_"+HttpUtil.getIp(request);
		Integer requestCount=(Integer) cacheHelper.get(key, Integer.class);
		if(requestCount!=null)
		{
			if(requestCount>=MAX_REQUEST_COUNT)
				return false;
			
			cacheHelper.incr(key, 1);
		}
		else
			cacheHelper.set(key, 1, REQUEST_INTERVAL);
		
		return true;
	}
	
}